package org.freedoit.server.service.task;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freedoit.server.om.User;
import org.freedoit.server.service.data.TaskReturnResult;
import org.freedoit.shared.data.SharedTask;
import org.freedoit.shared.util.Constants;

import com.google.gson.Gson;

public abstract class TaskServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5003094136199773219L;

	private static final Logger log = Logger.getLogger(TaskServlet.class.getName());

	/**
	 * 
	 */
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		String message = request.getParameter(Constants.JSON_DATA_KEY);
		log.warning(message);
		TaskReturnResult result = new TaskReturnResult();
		Gson gson = new Gson();
		if (message == null) {
			result.setCode(TaskReturnResult.CODE_INVALID_REQUEST);
		} else {
			SharedTask sharedTask = null;
			try {
				sharedTask = gson.fromJson(message, new com.google.gson.reflect.TypeToken<SharedTask>() {  
					}.getType());
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if (sharedTask == null) {
				result.setCode(TaskReturnResult.CODE_INVALID_REQUEST);
			} else {
				Long currentUserId = getCurrentUserId(request);
				log.warning("" + currentUserId);
				if (currentUserId == null) {
					result.setCode(TaskReturnResult.CODE_lOGIN_REQUIRED);
				} else {					
					Long timestamp = new Long(System.currentTimeMillis());					
					// 
					workOnTask(sharedTask, currentUserId, result, timestamp);
				}
			}
		}
		
		response.getWriter().write(gson.toJson(result,  new com.google.gson.reflect.TypeToken<TaskReturnResult>() {  
					}.getType()));
	}
	
	private Long getCurrentUserId(HttpServletRequest request)
	{
		User currentUser = (User)(request.getSession().getAttribute(Constants.DOIT_USER_KEY));
		if (currentUser == null) {
			return null;
		} else {
			return currentUser.getUserId();
		}
		
	}
	
	protected abstract void workOnTask(SharedTask sharedTask, Long currentUserId, TaskReturnResult result, Long timestamp);
}
